package com.example.SocialApplication.adapters;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.SocialApplication.R;
import com.example.SocialApplication.db.entity.Thing;
import com.example.SocialApplication.db.entity.ThingMain;

import java.io.File;
import java.util.List;

public class ThingsAdapter extends ArrayAdapter {
    private List<ThingMain> mListThings;
    private Context mContext;

    public ThingsAdapter(Context context, int textViewResourceId, List<ThingMain> objects) {
        super(context, textViewResourceId, objects);
        this.mListThings = objects;
        this.mContext = context;
    }

    @Override
    public ThingMain getItem(int position) {
        return mListThings.get(position);
    }

    @Override
    public int getCount() {
        return mListThings.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = ((Activity) mContext).getLayoutInflater().inflate(R.layout.color_spectrum_item, parent, false);
        }

        LinearLayout layout = (LinearLayout) view.findViewById(R.id.background_layout);
        ImageView image = (ImageView) view.findViewById(R.id.imageView);
        TextView name = (TextView) view.findViewById(R.id.name);

        layout.setBackgroundColor(Color.parseColor(getItem(position).getColor()));
        image.setImageBitmap(getBitmap(getItem(position).getPictureId()));
        name.setText(getItem(position).getName());

        return view;
    }

    private Bitmap getBitmap(String name) {
        String pathToFolder = mContext.getExternalCacheDir().getAbsolutePath()
                + File.separator
                + "images"
                + File.separator;

        String fileName = File.separator + name + ".png";
        String path = pathToFolder + fileName;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        Bitmap result = BitmapFactory.decodeFile(path, options);
        return result;
    }
}
